<template>
	<view class="send">
		<view class="head">
			<view>寄件</view>
			<view class="circle-btn">
				<text class="txt" @click="back">返</text>
			</view>
		</view>

		<view class="info-area">

			<view class="save-warehouse">

				<!-- 服务店自寄  -->
				<view class="input-area" v-if="this.way == 0">
					<view class="circle-btn linear-gradient-back">
						<text class="txt">收</text>
					</view>
					<!-- <input  placeholder="保存到哪个仓库" class="my-input" placeholder-style="color: rgba(255,255,255, 0.8);"/> -->
					<picker :range="showWarehouseNames" :value="selectedWarehouseIndex" @change="onWarehouseChange"
						class="my-big-picker">
						<view class="picker">

							<!-- <text class="title">{{
							selectedWarehouseIndex === -1  ? '保存到哪个仓库'
							: wareHouseList[selectedWarehouseIndex].wareHouseName
						}}</text> -->

							<text v-if="selectedWarehouseIndex === -1"
								style="color: rgba(255, 255, 255, 0.4)">保存到哪个仓库</text>
							<text v-else class="title"> {{wareHouseList[selectedWarehouseIndex].wareHouseName}} </text>

							<view class="triangle-down"></view>
						</view>
					</picker>

				</view>

				<!-- 上门取件 -->
				<view v-if="this.way == 1">
					<view class="input-area">
						<view class="circle-btn">
							<text class="txt">寄</text>
						</view>
						<input v-model="pickUpAddress" placeholder="从哪里寄出" class="my-big-picker"
							placeholder-style="color: rgba(255,255,255, 0.6);" />
					</view>

					<view class="input-area">
						<view class="circle-btn circle-btn-black">
							<text class="txt">收</text>
						</view>


						<!-- <input  placeholder="要寄到哪里去" class="my-input" placeholder-style="color: rgba(255,255,255, 0.8);"/> -->
						<picker :range="showWarehouseNames" :value="selectedWarehouseIndex" @change="onWarehouseChange"
							class="my-big-picker">
							<view class="picker">

								<text v-if="selectedWarehouseIndex === -1"
									style="color: rgba(255, 255, 255, 0.4)">要寄到哪里去</text>
								<text v-else class="title"> {{wareHouseList[selectedWarehouseIndex].wareHouseName}}
								</text>

								<view class="triangle-down"></view>
							</view>
						</picker>
					</view>

				</view>



			</view>
		</view>

		<view class="ways">
			<view class="fade-white-font-color">寄件方式</view>
			<view class="way" :class="[ this.way == 0  ? 'active' : '']" @click="()=> this.way = 0"> 服务点自寄 </view>
			<view class="way" :class="[ this.way == 1 ? 'active' : '']" @click="()=> this.way = 1"> 上门取件</view>
		</view>

		<view class="info-form">
			<form @submit="formSubmit">
				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">物品信息</view>
							<view class="requiedFlag">
								必填
							</view>
						</label>
					</view>

					<view class="input-area">
						<input v-model="formData.goodName" placeholder="请输入物品信息"
							placeholder-style="color: rgba(255,255,255, 0.6);" />
						<!-- 普通选择器 -->
						<!--    <picker :range="eltrInfoOptions.map(item => item.label)" :value="selectedIndex" @change="onPickerChange">
						          <view class="picker">
						            <text v-if="selectedIndex === -1">请选择 > </text>
						            <text v-else>{{ eltrInfoOptions[selectedIndex].label }}</text>
						          </view>
						        </picker> -->

					</view>
				</view>

				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">储存时间</view>
							<view class="requiedFlag">
								必填
							</view>
						</label>
					</view>

					<view class="input-area">
						<!-- <input v-model="formData.saveTime" placeholder="xxx"  placeholder-style="color: rgba(255,255,255, 0.8);" /> -->
						<picker mode="date" :value="formData.storageTime" :start="getTodayDate()" end="2035-12-31"
							@change="onDateChange($event, 'storageTime')">
							<view class="picker">
								<text v-if="!formData.storageTime" style="color: rgba(255, 255, 255, 0.4)">请选择储存时间 ></text>
								<text v-else>{{ formData.storageTime }}</text>
							</view>
						</picker>
					</view>
				</view>

				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">联系人</view>
							<view class="requiedFlag">
								必填
							</view>
						</label>
					</view>

					<view class="input-area">
						<input v-model="formData.contactPerson" placeholder="请输入联系人"
							placeholder-style="color: rgba(255,255,255, 0.6);" />
					</view>
				</view>

				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">手机号</view>
							<view class="requiedFlag">
								必填
							</view>
						</label>
					</view>

					<view class="input-area">
						<input v-model="formData.contactPhone" placeholder="请输入手机号"
							placeholder-style="color: rgba(255,255,255, 0.6);" />
					</view>
				</view>

				<view class="form-item" v-if="this.way == 1">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">上门时间</view>
							<view class="requiedFlag">
								必填
							</view>
						</label>
					</view>

					<view class="input-area" @click="open">

						<!-- <input v-model="formData.appointmentTime"  placeholder="xxxx" placeholder-style="color: rgba(255,255,255, 0.8);" />
						 -->
						<!-- <picker mode="date" :value="formData.appointmentTime" start="2015-01-01" end="2035-12-31" @change="onDateChange($event, 'appointmentTime')">
							<view class="picker">
								<text v-if="!formData.appointmentTime" style="color: rgba(255, 255, 255, 0.4)">请选择 ></text>
								<text v-else>{{ formData.appointmentTime }}</text>
							</view>
						  </picker> -->
						<text v-if="!formData.appointmentTime" style="color: rgba(255, 255, 255, 0.4)">请选择上门时间 ></text>
						<text style="color: white;" v-else>{{ formData.appointmentTime }}</text>

						

					</view>
				</view>

				<view class="form-item">
					<view class="label-area">
						<label>
							<view class="txt fade-white-font-color">备注</view>
							<!-- <view class="requiedFlag">
							  必填
						  </view> -->
						</label>
					</view>

					<view class="input-area">
						<input v-model="formData.remark" placeholder="请输入备注"
							placeholder-style="color: rgba(255,255,255, 0.6);" />
					</view>
				</view>
			</form>

        <liuDeliveryTime @change="appointmentTimeChange" ref="chooseTime" title="请选择上门时间">
						</liuDeliveryTime>
		</view>


		<view class="order">
			<!-- <view class="orderHelp">
				<view class="title">填写收寄地址后看预估费用</view>
				<view class="tip fade-white-font-color">按照一公斤内物品 + 存储天数估计 </view>
			</view> -->

			<view class="order-btn linear-gradient-order" @click="formSubmit">
				立即下单
			</view>
		</view>
	</view>
</template>

<script>
	import * as api from '../../utils/api.js'
	import { checkPhone } from '../../utils/untils.js';
	import liuDeliveryTime from '../../components/liu-delivery-time.vue';

    

	export default {
		components: {
			liuDeliveryTime
		},
		data() {
			return {
				wareHouseList: [],
				selectedWarehouseIndex: -1,
				eltrInfoOptions: [{
						label: '苹果',
						value: 'apple'
					},
					{
						label: '香蕉',
						value: 'banana'
					},
					{
						label: '橙子',
						value: 'orange'
					}
				],
				options: ['苹果', '香蕉', '橙子', '葡萄'],
				way: 0, // 0 服务店自寄 1 上门取件
				selectedIndex: -1, // 给电子信息产品使用的
				pickUpAddress: '',
				formData: {
					goodName: '',
					storageTime: this.getTodayDate(3),
					contactPerson: null,
					contactPhone: null,
					appointmentTime: this.getDefaultAppointTime(),
				}
			}
		},
		computed: {
			showWarehouseNames() {
				if (!this.wareHouseList || !this.wareHouseList.length) return []
				return this.wareHouseList.map(item => item.wareHouseName);
			},
		},
		onLoad() {
			this.getWareHouseList()
		},
		methods: {
			open() {
				this.$refs.chooseTime.open()
			},
			appointmentTimeChange(e) {
				this.formData.appointmentTime = e.value;
			},
			async getWareHouseList() {
				const res = await api.wareHouseList();
				this.wareHouseList = res.rows || [];
			},
			onWarehouseChange(e) {
				this.selectedWarehouseIndex = e.detail.value;
			},
			onPickerChange(e) {
				// 更新选中的索引
				this.selectedIndex = e.detail.value;
				// 根据索引获取实际选中的值
				this.formData.eltrInfo = (this.eltrInfoOptions[this.selectedIndex])?.value;
				console.log('你选择的实际值是：', this.formData.eltrInfo);
			},
			// 获取指定偏移天数后的日期的方法
			getTodayDate(offset = 0) {
				const date = new Date();
				// 根据偏移量调整日期
				date.setDate(date.getDate() + offset);
				const year = date.getFullYear();
				// 月份从 0 开始计数，所以要加 1
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			getDefaultAppointTime() {
				const hour = this.getTodayHour();
				return this.getTodayDate(0) + ` ${hour}:00`;
			},

			getTodayHour() {
				const currentDate = new Date();
				const currentHour = currentDate.getHours();
				return currentHour;
			},
			onDateChange(e, prop) {
				this.formData[prop] = e.detail.value;
				console.log('你选择的日期是：', this.formData[prop]);
			},
			back() {
				uni.navigateBack()
			},
			// chackForm 检查表单提交的有效值
			checkForm() {
				let errMsg = ''
				if (!this.formData.goodName) {
					errMsg = '物品信息必填'
				}
				if (!this.formData.storageTime) {
					errMsg = '预计存储至时间必填'
				}
				if (!this.formData.contactPerson) {
					errMsg = '联系人必填必填'
				}
				if (!this.formData.contactPhone || checkPhone(this.formData.contactPhone)) {
					errMsg = '手机号格式不正确'
				}
				if (this.way ==1 && !this.formData.appointmentTime) {
					errMsg = '上门时间必填'
				}

				if (errMsg) {
					this.myToast(errMsg);
				}

				return !errMsg;

			},
			// 提交成功后，跳转到下单成功页面
			async formSubmit(e) {
				const token = uni.getStorageSync('token');
				if (!token) {
					uni.redirectTo({
						url: '/pages/login/index'
					});
					return;
				}
				
				const selectedWarehouse = this.wareHouseList[this.selectedWarehouseIndex];
				if (!selectedWarehouse || !selectedWarehouse.wareHouseId) {
					this.myToast(this.way == 1 ? '您还没有选择从哪里寄出' : '您还没有选择要保存的仓库！')
					return
				}

				const pass = this.checkForm();
				if (!pass) return
				const formData = this.formData;
				const params = {
					wareHouseId: selectedWarehouse.wareHouseId,
					relicMethod: this.way == 1 ? 1 : 2,
					...formData
				};


				if (this.way == 0) {} // 服务店自寄		
				if (this.way == 1) { // 上门取件
					if (!this.pickUpAddress) {
						return this.myToast('您还没有选择要寄到哪里去')
					}
					params.pickUpAddress = this.pickUpAddress;

				}

				
				const res = await api.insertRelicOrder(params);

				this.successCb(res, params.wareHouseId)
			},

			successCb(res, wareHouseId) {
				this.myToast(res.msg);
				if (!res.code == 200) return

				const scene = this.way ? 'take' : 'mail';
				const url = `/pages/orderFeedback/index?scene=${scene}&wareHouseId=${wareHouseId}`;
				uni.navigateTo({
					url: url,
					success() {
						console.log('跳转成功');
					},
					fail(err) {
						console.error('跳转失败', err);
					}
				});
			},

			myToast(msg, icon = 'none') {
				uni.showToast({
					icon: icon,
					title: msg,
					duration: 2000
				})
			},


		}
	}
</script>

<style lang="scss">
	.send {
		color: white;
		padding: 40rpx 20rpx;
		align-items: center;


		.circle-btn {
			width: 90rpx;
			height: 90rpx;
			border-radius: 50%;
			text-align: center;
			line-height: 90rpx;
			background-color: #e7b34d;

			.txt {
				color: black;
				font-size: 22px;
			}
		}

		.circle-btn-black {
			background-color: rgba(0, 0, 0, 0.8);

			.txt {
				color: white;
			}
		}

		.sqaure-btn {
			width: 90rpx;
			height: 90rpx;
			border-radius: 8rpx;
			background-color: yellow;
			text-align: center;
			line-height: 90rpx;
			font-size: 40rpx;
			background-color: rgba(0, 0, 0, 0.8);

			.txt {
				color: white;
			}
		}

		// .linear-gradient-back {
		// 	background: linear-gradient(to bottom right, #f2ebce, #856925);
		// }

		// .linear-gradient-order {
		// 	background: linear-gradient(to bottom right, #ede5c1, #f8ce3d);
		// }

		.head {
			display: flex;
			padding: 40rpx 10rpx;
			justify-content: space-between;
			font-size: 46rpx;
		}

		.info-area {
			padding: 40rpx 10rpx;
			border-radius: 10rpx;

			.save-warehouse {
				.my-big-picker {
					font-size: 42rpx;
					color: white;
				}

				.input-area {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin: 20rpx 0 20rpx 0;
					padding: 16rpx 20rpx;
					border-radius: 10rpx;
					background-color: #333333;

					.my-input {
						font-size: 42rpx;
					}
				}
			}
		}

		.ways {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 40rpx;
			margin: 60rpx 0;
			padding: 40rpx 10rpx;
			border-radius: 10rpx;
			background-color: rgba(0, 0, 0, 0.3);

			.way {
				color: white;
				border-radius: 8px;
				padding: 6px 30rpx;
				background-color: #2f2f2f;
			}

			.active {
				background-color: #e7b34d;
				color: black;
				// box-shadow: 2px 2px 2px 2px rgba(0, 0, 0, 0.5);  
			}
		}


		.info-form {
			font-size: 30rpx;
			padding: 40rpx 20rpx;
			border-radius: 10rpx;
			background-color: #333333;

			.form-item {
				display: flex;
				align-items: center;
				margin: 20rpx 0;

				.label-area {
					.txt {
						width: 5em;
						display: inline-block;
					}

					.requiedFlag {
						padding: 0 30rpx;
						display: inline-block;
						border-radius: 30rpx;
						background-color: #ff2b1d;
						color: white;
					}
				}

				.input-area {
					flex: 1;
					margin-left: 1em;
				}
			}
		}

		.order {
			position: fixed;
			bottom: 30rpx;
			right: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-radius: 10rpx;
			padding: 20rpx 22rpx;
			/* 适配安全区 */
			// padding-bottom: constant(safe-area-inset-bottom);
			// padding-bottom: env(safe-area-inset-bottom);
			background-color: rgba(0, 0, 0, 0.3);

			//  .orderHelp {
			// .title {
			// 	font-size: 34rpx;
			// }
			// .tip {
			// 	font-size: 24rpx;
			// }  
			//  }
			.order-btn {
				padding: 5rpx 40rpx;
				display: inline-block;
				border-radius: 30rpx;
				background-color: #e7b34d;
				color: black;
				font-size: 40rpx;
				font-weight: bold;
			}
		}
	}
</style>